<template>
  <BasicDrawer
      :destroyOnClose="true"
      v-bind="$attrs"
      @register="registerDrawer"
      showFooter
      :title="title"
      width="680px"
      @ok="onSave"
      okText="保存"
      :maskClosable="false"
  >
    <div class="card">
      <BasicForm @register="registerForm1" class="form">
        <template #tag="{ model, field }">
          <div class="tag">
            <div
                :class="[
                'use',
                'cell',
                exist(o.name, model[field]) ? 'active tri-active-2' : 'tacit',
              ]"
                v-for="o in labelListDS"
                :key="o.id"
                @click="onToggle(model, field, o)"
            ><span>{{ o.name }}</span>

              <div class="tri-symbol-2"></div>
              <div v-if="exist(o.name, model[field])" class="tri-checked-2">
                <CheckOutlined/>
              </div>
            </div>

            <a-button
                type="primary"
                @click="
                () => {
                  tagName = null;
                  isAdd = true;
                }
              "
            >
              <template #icon>
                <PlusOutlined/>
              </template>
              新增标签
            </a-button>
          </div>
        </template>
      </BasicForm>
    </div>

    <div class="card" v-if="isAdd" style="padding: 8px 0 8px 115px">
      <div class="add">
        <a-flex gap="middle" align="center">
          <a-input v-model:value.trim="tagName" placeholder="请输入标签名称"/>
          <div>
            <a @click="onAddTag">确定</a>
            <a-divider type="vertical"/>
            <a @click="isAdd = false">取消</a>
          </div>
        </a-flex>
      </div>
    </div>
  </BasicDrawer>
</template>
<script>
import {defineComponent, reactive, ref, toRefs} from 'vue';
import {BasicForm, useForm} from '@/components/Form/index';
import {BasicDrawer, useDrawerInner} from '@/components/Drawer';
import {CheckOutlined, PlusOutlined} from '@ant-design/icons-vue';

import {POST} from '@/api/http.js';
import {useMessage} from '@/hooks/web/useMessage';
import {exist} from '@/api/util.js';

export default defineComponent({
  components: {BasicDrawer, BasicForm, CheckOutlined, PlusOutlined},
  emits: ['complete'],
  setup(_, {emit}) {
    const state = reactive({
      title: '',
      behavior: 'edit',
      memberCode: null,
      labelList: [],
      isAdd: false,
      tagName: null,
    });

    const {createMessage} = useMessage();

    const [registerForm1, form1] = useForm({
      labelWidth: 100,
      baseColProps: {span: 24, style: {paddingRight: '36px'}},

      schemas: [
        {
          label: '选择标签',
          field: 'labelList',
          required: false,
          component: 'CheckboxGroup',
          slot: 'tag',
        },
      ],
      showActionButtonGroup: false,
    });

    const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(
        async ({memberCode, labelList}) => {
          labelList ||= [];

          Object.assign(state, {title: '客户标签', memberCode, labelList});
          await init();
        },
    );

    async function init() {
      await form1.resetFields();

      const {labelList} = state;
      const initData = {labelList};

      form1.setFieldsValue(initData);
      await loadLabelList();
    }

    const labelListDS = ref([]);

    async function loadLabelList() {
      try {
        setDrawerProps({confirmLoading: true});

        labelListDS.value = (await POST('/membership/getStoreLabelList')) ?? [];
      } finally {
        setDrawerProps({confirmLoading: false});
      }
    }

    function onToggle(model, field, item) {
      const index = model[field].findIndex((s) => s === item.name);

      if (index > -1) {
        model[field].splice(index, 1);
      } else {
        model[field].push(item.name);
      }
    }

    async function onSave() {
      const {memberCode} = state;

      await form1.validate();
      const {labelList} = form1.getFieldsValue();

      try {
        setDrawerProps({confirmLoading: true});

        const labels = labelListDS.value
            .filter((o) => exist(o.name, labelList))
            .map(({id, name}) => ({id, name}));
        await POST('/membership/addMemberLabelInfo', {memberCode, labels});

        createMessage.success('标签已保存');
        emit('complete');
        closeDrawer();
      } finally {
        setDrawerProps({confirmLoading: false});
      }
    }

    async function onAddTag() {
      const {tagName} = state;

      if (!tagName) {
        return createMessage.error('请输入标签名称');
      }

      try {
        await POST('/membership/addStoreLabelInfo', {name: tagName});
        createMessage.success('标签已保存');
        state.isAdd = false;
      } finally {
        await loadLabelList();
      }
    }

    return {
      ...toRefs(state),
      labelListDS,
      registerDrawer,
      registerForm1,
      onSave,
      onToggle,
      exist,
      onAddTag,
    };
  },
});
</script>

<style lang="less" scoped>
.card {
  margin: 8px;
  padding: 0 12px;

  .form {
    padding: 24px 12px 0 0;
  }

  .tag {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    cursor: pointer;
    gap: 8px 12px;

    .cell {
      position: relative;
      overflow: clip;

      padding: 4px 20px;
      border-radius: 4px;
      font-size: 13px;
      font-weight: 400;
    }

    .tacit {
      border: 1px solid #ced2d9;
      color: #666666;
    }

    .active {
      background: #fff1f4;
      border-radius: 2px;
      border: 1px solid #ffdfe7;
      color: #eb6485;
    }
  }

  .add {
    margin: 12px 64px 12px 0;
    background: #f5f7fa;
    border-radius: 6px;
    padding: 12px 18px;
  }
}
</style>
